# -*- coding: utf8 -*-

import ctypes

__author__ = 'sergey'

_libc = ctypes.CDLL( 'libc.so.6' )

__setaffinity = _libc.sched_setaffinity
__setaffinity.argtypes = [ctypes.c_int, ctypes.c_size_t, ctypes.POINTER(ctypes.c_size_t)]

__getaffinity = _libc.sched_getaffinity
__getaffinity.argtypes = [ctypes.c_int, ctypes.c_size_t, ctypes.POINTER(ctypes.c_size_t)]

def get_affinity(pid=0):
    mask = ctypes.c_ulong(0)                        # инициализируем переменную
    c_ulong_size = ctypes.sizeof(ctypes.c_ulong)    # данные только по первым 32/64 ядрам
    if __getaffinity(pid, c_ulong_size, mask) < 0:
        raise OSError
    return mask.value                               # преобразование ctypes.c_ulong => python int

def set_affinity(pid=0, mask=1):
    mask = ctypes.c_ulong(mask)
    c_ulong_size = ctypes.sizeof(ctypes.c_ulong)
    if __setaffinity(pid, c_ulong_size, mask) < 0:
        raise OSError
    return